package org.docshare.view;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.PatternMatcher;
import android.util.Log;

public class Book {
	int res_id ;
	Context context=null;
	String data = null;
	int cur_pos = 0; //read at here
	String[] caps = null;
	int[] caps_pos = null;
	static Book ins = null;
	String assets_file = "book.txt";
	
	public static Book getLastIns(Context context,int res_id)
	{
		if(ins == null) return new Book(context,res_id);
		
		ins.context = context;
		ins.res_id = res_id;
		ins.assets_file = null;
		return ins;
	}
	
	public static Book getLastIns(Context context,String assets_file)
	{
		if(ins == null) return new Book(context,assets_file);
		
		ins.context = context;
		ins.res_id = -1;
		ins.assets_file = assets_file;
		return ins;
	}
	
	
	public String getData()
	{
		return data;
	}
	public Book(Context context,int res_id)
	{
		ins = this;
		this.res_id = res_id;
		this.assets_file = null;
		this.context =context;
	}
	public Book(Context context, String assets_file) {
		ins  = this;
		this.res_id = -1;
		this.assets_file = assets_file;
		this.context = context;
	}

	public String[] getCapsNew3(){
		int last_start = 0;
		String cur_mulu = "";
		String cur_pianming = "";

		ArrayList<String> ret = new ArrayList<String>();

		try {
			InputStreamReader inputReader = new InputStreamReader(getBookInputStream(),"gb2312");
			BufferedReader bufReader = new BufferedReader(inputReader);
			String l="";
			String Result="";
			StringBuffer sb = new StringBuffer();
			while((l = bufReader.readLine()) != null)
			{
				if(l.startsWith("<Ŀ¼>"))
				{
					if(l.length() > 4){
						cur_mulu = l.substring(4);
					}
					continue;
				}
				if(l.startsWith("<ƪ��>"))
				{
					if(l.length() > 4){
						cur_pianming = l.substring(4);
						if(cur_mulu.length() > 0)
						{
							ret.add(cur_mulu + "-" + cur_pianming);
						}else{
							ret.add( cur_pianming);
							
						}
					}
					continue;
				}
			}
		} catch (Exception e) {
			try{
				Log.e("book",e.toString());
			}catch(Exception ee){
				
			}
			e.printStackTrace();
		}
		
		if(ret.size() == 0){
			caps = new String[]{"ȫ��"};
			caps_pos = new int[]{0};
			return caps;
		}
		String[] sret = new String[ret.size()];

		caps= ret.toArray(sret);
		
		return caps;
	}
	public String[] getCapsNew2()
	{
		//if(caps != null) return caps;
		ArrayList<Integer> ret_pos = new ArrayList<Integer>();
		
		ArrayList<String> ret = new ArrayList<String>();
		String[] lines = data.split("\n");
		String cur_mulu = "";
		String cur_pianming = "";
		
		for(String s : lines){
			if(s.startsWith("<Ŀ¼>"))
			{
				if(s.length() > 4){
					cur_mulu = s.substring(4);
				}
				continue;
			}
			if(s.startsWith("<ƪ��>"))
			{
				if(s.length() > 4){
					cur_pianming = s.substring(4);
					if(cur_mulu.length() > 0)
					{
						ret.add(cur_mulu + "-" + cur_pianming);
					}else{
						ret.add( cur_pianming);
						
					}
				}
				continue;
			}
		}
		if(ret.size() == 0){
			caps = new String[]{"ȫ��"};
			caps_pos = new int[]{0};
			return caps;
		}
		String[] sret = new String[ret.size()];

		caps= ret.toArray(sret);
		return caps;		
	}
	public String[] getCapsNew()
	{
		if(caps != null) return caps;
		ArrayList<Integer> ret_pos = new ArrayList<Integer>();
		
		ArrayList<String> ret = new ArrayList<String>();
		String pat = "<ƪ��>(.+?)\n";
		Pattern pattern = Pattern.compile(pat);
		Matcher ms = pattern.matcher(data);
		while(ms.find())
		{
			ret.add(ms.group());
			ret_pos.add(ms.start());
		}
		if(ret.size() == 0){
			caps = new String[]{"ȫ��"};
			caps_pos = new int[]{0};
			return caps;
		}
		String[] sret = new String[ret.size()];
		caps_pos= new int[ret.size()];
		caps= ret.toArray(sret);
		for(int i=0;i<ret.size();i++){
			caps_pos[i] = ret_pos.get(i);
		}
		
		return caps;		
	}
	public String[] getCaps()
	{
		if(caps != null) return caps;
		
		//else
		caps_pos = null;
		String[] c =getCapsOld();
		if(c.length < 5)
		{
			String[] c2 = getCapsNew2();
			if(c2.length < c.length){
				caps = c;
				
			}else{
				caps_pos = null;
				caps = c2;
			}
		}
		return caps;
	}
	public String[] getCapsOld()
	{
		if(caps != null) return caps;
		
		loadData();
		ArrayList<String> ret = new ArrayList<String>();
		String pat = "��(\\d+?)��(.+?)\n";
		Pattern pattern = Pattern.compile(pat);
		Matcher ms = pattern.matcher(data);
		while(ms.find())
		{
			ret.add(ms.group());
		}
		if(ret.size() == 0){
			caps = new String[]{"ȫ��"};
			caps_pos = new int[]{0};
			return caps;
		}
		String[] sret = new String[ret.size()];
		caps= ret.toArray(sret);
		return caps;		
	}
	
	public int findCapPosition(int cap_id){
		if(caps_pos != null){
			return caps_pos[cap_id];
		}
		String c = caps[cap_id];
		if(c.indexOf('-')> 0){
			c = c.substring(c.indexOf('-')+1);
		}
		int p = data.indexOf("<ƪ��>" + c);
		if(p > 0) return p;
		
		return data.indexOf(c);
	}
	private void loadData()
	{
		if(data != null) return;
		
		data = readAll(res_id);
	}
	private InputStream getBookInputStream(){
		if(res_id > 0){
			return context.getResources().openRawResource(res_id);
		}
		if(assets_file != null){
			AssetManager assetManager = context.getAssets();
			try {
				return assetManager.open(assets_file);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			}
		}
		
		return null;
		
	}
	private String readAll(int id)
	{
		try {
			InputStreamReader inputReader = new InputStreamReader( getBookInputStream(),"gb2312");
			BufferedReader bufReader = new BufferedReader(inputReader);
			String line="";
			String Result="";
			StringBuffer sb = new StringBuffer();
			while((line = bufReader.readLine()) != null)
			{
				sb.append(line+"\n");
			}
			bufReader.close();
			inputReader.close();
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	public void setCurCap(int capid) {
		cur_pos = findCapPosition(capid);		
	}
	public int getCurPos() {
		return this.cur_pos;
	}
	
}
